const Controller = require('egg').Controller;

var svgCaptcha = require('svg-captcha');

class FileController extends Controller {

    async auth () {
        this.ctx.redirect('http://cardv2.oss-cn-hangzhou.aliyuncs.com/fileauth.txt');
    }

    async apiclientCert () {
        this.ctx.redirect('http://weshop88.oss-cn-hangzhou.aliyuncs.com/apiclient_cert.p12');
    }


    async shangkechuangyi () {
    	this.ctx.body = 'Whv6QEeRIBYh4ekU';
    }


    async detail () {

    	const { ctx } = this;

    	const name = ctx.params[0] + '.txt';

    	const content = await ctx.service.company.domainFile(name);

    	if(content == undefined) {
    		this.ctx.body = '没有设置文件名和文件内容';
    	}else{
    		this.ctx.body = content.filecontent;
    	}
    }


    async getImageCode () {

        const { ctx } = this;
        const options = ctx.request.body.options;

        const c = svgCaptcha.create(options);

        ctx.helper.success(c);
    }


    async setRegisterSmsCode () {

        const { ctx, app } = this;

        const mobile = ctx.request.body.mobile;

        const noncestr = await ctx.service.util.uuid(4, 10);

        await app.redis.get('tmp').set('dlq_register_code_' + mobile, noncestr);

        //10分钟有效。
        await app.redis.get('tmp').expire('dlq_register_code_' + mobile, 10 * 60);

        let content = '验证码' + noncestr + '，您正在注册成为新用户，感谢您的支持！';

        let sentSmsState = 1;   //0:发送失败，1:发送成功
        let sentSmsFailMsg = '';
        let r = {};

        try{
            r = await ctx.service.sms.send({
                mobile, 
                'info' : {
                    'code' : noncestr,
                }, 
                'templateCode' : 'SMS_148730594',
            });
        }catch (err){
            ctx.logger.info('异常');
            sentSmsState = 0;
            sentSmsFailMsg = err.code;
            r = err.data;
        }

        ctx.logger.info(r);

        const p = {
            mobile, 
            content, 
            'requestid' : r.RequestId, 
            'code' : r.Code, 
            'message' : r.Message, 
            'bizid' : r.BizId, 
            'order_code' : '',
            'state' : sentSmsState,
            'failmsg' : sentSmsFailMsg,
        };

        const r2 = await ctx.service.sms.savelog(p);

        if(sentSmsState == '1'){
            ctx.helper.success('1');
        }else{
            ctx.helper.error(sentSmsFailMsg);
        }
        
    }


    async getRegisterSmsCode () {

        const { ctx, app } = this;

        const mobile = ctx.request.body.mobile;

        const result = await app.redis.get('tmp').get('dlq_register_code_' + mobile);

        ctx.helper.success(result);
    }
    
}
module.exports = FileController;